package com.yiguantong.police.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.MainApplication;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hb.dialog.myDialog.ActionSheetDialog;
import com.mt.mtloadingmanager.LoadingManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yiguantong.police.BaseActivity;
import com.yiguantong.police.contact.Contact;
import com.yiguantong.police.contact.ContactUtil;
import com.yiguantong.police.nfc.NfcActivity;
import com.yiguantong.police.ui.utils.MyLog;
import com.yiguantong.police.ui.utils.PictureCompressUtil;
import com.yiguantong.police.ui.utils.UriUtils;
import com.yiguantong.police.webview.ActivityResult;
import com.yiguantong.police.webview.RxActivityResult;
import com.yiguantong.police.R;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends BaseActivity {

    private WebView webView;
    private LinearLayout loadimg;
    private MainActivity.JavaScriptObject javascriptObject;
    private WebSettings webSettings;

    private String imageFilePath;
    private String webHookKey;

    //webView中二维码扫描核销功能
    public static final int REQUEST_CODE_RECORD_QRCODE = 209;
    //webView中NFC核销功能
    public static final int REQUEST_CODE_RECORD_NFC = 210;
    //webView中文件上传功能
    public static final int REQUEST_CODE_RECORD_FILE = 211;
    //Video视频录制
    public static final int REQUEST_CODE_RECORD_VIDEO = 104;

    public static final int REQUEST_CODE_RECORD_ALBUM = 103;

    public static final int REQUEST_CODE_RECORD_CAMERA = 102;

    private LoadingManager loadingManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        loadimg.setVisibility(View.VISIBLE);
        initWebParams();
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();

        StrictMode.setVmPolicy(builder.build());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder.detectFileUriExposure();
        }

        loadingManager = new LoadingManager(this);
    }

    @SuppressLint("JavascriptInterface")
    private void initView() {
        webView = findViewById(R.id.webView);
        loadimg = findViewById(R.id.loading_img);
        javascriptObject = new MainActivity.JavaScriptObject(this);
        webView.addJavascriptInterface(javascriptObject, "javascriptObject");

        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {  //表示按返回键
                        webView.goBack();   //后退
                        return true;    //已处理
                    }
                }
                return false;
            }
        });
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initWebParams() {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }
        loadimg.setVisibility(View.VISIBLE);
        loadUrl(this.getString(R.string.home_url));

        webSettings = webView.getSettings();
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webView.setInitialScale(25);
        webView.getSettings().setUseWideViewPort(true);


        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //webSettings.setAllowFileAccess(true);
        webSettings.setSavePassword(false);
        // 修补WebView域控制不严格漏洞
        webSettings.setAllowFileAccess(false);
        webSettings.setAllowFileAccessFromFileURLs(false);
        webSettings.setAllowUniversalAccessFromFileURLs(false);

        webSettings.setSaveFormData(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDefaultFontSize(18);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSettings.setBlockNetworkImage(false);
        //VIVO Y35等低端机型第三方页面如果样式不标准可能出现样式问题
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        setParam();
        if (Build.VERSION.SDK_INT >= 19) {
            // webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        }
        webSettings.setJavaScriptEnabled(true);
        webView.requestFocus();
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
        webSettings.setLoadsImagesAutomatically(true); //自动加载图片
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    MyLog.i("加载完成1。。。。。");
                    loadimg.setVisibility(View.GONE);
                } else {
                    loadimg.setVisibility(View.VISIBLE);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
    }

    private void setParam() {
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setUserAgentString(new WebView(this).getSettings().getUserAgentString());
        if (android.os.Build.VERSION.SDK_INT >= 11) {
            webSettings.setDisplayZoomControls(false);
        }
        //启用地理定位
        webSettings.setGeolocationEnabled(true);
        //设置定位的数据库路径
        webSettings.setGeolocationDatabasePath(dir);

        // 设置支持JavaScript
        webSettings.setAppCacheEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setMediaPlaybackRequiresUserGesture(false);
        // 设置定位的数据库路径
        // 最重要的方法，一定要设置，这就是出不来的主要原因

        // 把本类的一个实例添加到js的全局对象window中，
        // 移除高危JS接口
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        webView.removeJavascriptInterface("accessibility");
        webView.removeJavascriptInterface("accessibilityTraversal");

        webView.setFocusable(true);
        webView.setFocusableInTouchMode(true);
        webView.requestFocusFromTouch();
        webView.clearCache(true);
    }

    private void loadUrl(String url) {
        try {
            new URL(url);
        } catch (MalformedURLException e) {
            finish();
            return;
        }
        webView.loadUrl(url);
    }

    private class JavaScriptObject {
        private Context context;
        public String locationHook = null;

        public JavaScriptObject(Context context) {
            this.context = context;
        }

        //扫描二维码
        @JavascriptInterface
        public void normalTdcodeIgnoreLogin(final String hookKey) {
            RxPermissions.getInstance(context).request(Manifest.permission.CAMERA)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            if (granted) {
                                try {
                                    final Intent intent = new Intent(MainActivity.this, com.yiguantong.police.qrCode.ui.CaptureActivity.class);
                                    intent.putExtra("fromWebView", true);
                                    intent.putExtra("simpleScanner", true);
                                    RxActivityResult.startActivityForResult(MainActivity.this, intent, REQUEST_CODE_RECORD_QRCODE)
                                            .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                                            .subscribe(new Observer<ActivityResult>() {
                                                Disposable d;

                                                @Override
                                                public void onSubscribe(Disposable d) {
                                                    this.d = d;
                                                }

                                                @Override
                                                public void onNext(final ActivityResult activityResult) {
                                                    if (activityResult.getRequestCode() != REQUEST_CODE_RECORD_QRCODE)
                                                        return;
                                                    if (!d.isDisposed()) {
                                                        d.dispose();
                                                    }
                                                    if (activityResult != null && activityResult.isOk()) {
                                                        final Intent intent1 = activityResult.getData();
                                                        if (intent1 != null && !TextUtils.isEmpty(intent1.getStringExtra("sResult"))) {
                                                            runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    JSONObject jsonObject = new JSONObject();
                                                                    jsonObject.put("errorCode", 1);
                                                                    jsonObject.put("resultInfo", intent1.getStringExtra("sResult"));
                                                                    jsCallback(hookKey, jsonObject.toJSONString());
                                                                }
                                                            });
                                                        }
                                                    }
                                                }

                                                @Override
                                                public void onError(Throwable e) {
                                                    JSONObject jsonObject = new JSONObject();
                                                    jsonObject.put("errorCode", 0);
                                                    jsonObject.put("errorInfo", e.toString());
                                                    jsCallback(hookKey, jsonObject.toJSONString());
                                                }

                                                @Override
                                                public void onComplete() {

                                                }
                                            });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                jsCallback(hookKey, jsonObject.toJSONString());
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                                return;
                            }
                        }
                    });
        }

        //拍照
        @JavascriptInterface
        public void toHandleCamera(final String hookKey) {
            webHookKey = hookKey;
            RxPermissions.getInstance(context).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            if (granted) {
                                ActionSheetDialog dialog = new ActionSheetDialog(MainActivity.this).builder().setTitle("请选择")
                                        .addSheetItem("相册", null, new ActionSheetDialog.OnSheetItemClickListener() {
                                            @Override
                                            public void onClick(int which) {
                                                // 相册选取
                                                Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                                                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                                startActivityForResult(intent1, REQUEST_CODE_RECORD_ALBUM);
                                            }
                                        }).addSheetItem("拍照", null, new ActionSheetDialog.OnSheetItemClickListener() {
                                            @Override
                                            public void onClick(int which) {
                                                // 拍照
                                                //设置图片的保存路径,作为全局变量
                                                imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + new Date() + ".jpg";
                                                File temp = new File(imageFilePath);
                                                Uri imageFileUri = Uri.fromFile(temp);//获取文件的Uri
                                                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//跳转到相机Activity
                                                it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);//告诉相机拍摄完毕输出图片到指定的Uri
                                                startActivityForResult(it, REQUEST_CODE_RECORD_CAMERA);
                                            }
                                        });
                                dialog.show();
                            } else {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                jsCallback(hookKey, jsonObject.toJSONString());
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                                return;
                            }
                        }
                    });
        }

        //只能拍照
        @JavascriptInterface
        public void toHandleOnlyCamera(final String hookKey) {
            webHookKey = hookKey;
            RxPermissions.getInstance(context).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            if (granted) {
                                imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + new Date() + ".jpg";
                                File temp = new File(imageFilePath);
                                Uri imageFileUri = Uri.fromFile(temp);//获取文件的Uri
                                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//跳转到相机Activity
                                it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);//告诉相机拍摄完毕输出图片到指定的Uri
                                startActivityForResult(it, REQUEST_CODE_RECORD_CAMERA);
                            } else {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                jsCallback(hookKey, jsonObject.toJSONString());
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                                return;
                            }
                        }
                    });
        }

        //录像
        @JavascriptInterface
        public void handleVideo(final String hookKey) {
            webHookKey = hookKey;
            RxPermissions.getInstance(context).request(Manifest.permission.CAMERA)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            if (granted) {
                                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + new Date() + ".mp4";   // 保存路径
                                Uri uri = Uri.fromFile(new File(filePath));   // 将路径转换为Uri对象
                                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  // 表示跳转至相机的录视频界面
                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);    // MediaStore.EXTRA_VIDEO_QUALITY 表示录制视频的质量，从 0-1，越大表示质量越好，同时视频也越大
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);    // 表示录制完后保存的录制，如果不写，则会保存到默认的路径，在onActivityResult()的回调，通过intent.getData中返回保存的路径
                                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 30);   // 设置视频录制的最长时间
                                startActivityForResult(intent, REQUEST_CODE_RECORD_VIDEO);  // 跳转
                            } else {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                jsCallback(hookKey, jsonObject.toJSONString());
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                                return;
                            }
                        }
                    });
        }

        //获取手机通讯录
        @JavascriptInterface
        public void getPhoneContacts(final String hookKey) {
            RxPermissions.getInstance(context).request(Manifest.permission.READ_CONTACTS)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            JSONObject jsonObject = new JSONObject();
                            if (granted) {
                                List<Contact> contactList = new ContactUtil(context).getPhoneContacts();
                                jsonObject.put("errorCode", 1);
                                jsonObject.put("contactList", contactList);
                            } else {
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                            }
                            jsCallback(hookKey, jsonObject.toJSONString());
                        }
                    });
        }

        //异步获取定位信息
        @JavascriptInterface
        public void getLocation(final String key) {
            if (key == null || key.equals("")) {
                MainActivity.this.toast("未提供回调方法");
                return;
            }
            locationHook = key;
            location();
        }

        //推送到浏览器下载文件
        @JavascriptInterface
        public void exportUrl(final String url) {
            try {
                openBrowser(context, url);
            } catch (Exception e) {
                Toast.makeText(context.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }

        //NFC写卡
        @JavascriptInterface
        public void handleReadNFC(final String hookKey) {
            RxPermissions.getInstance(context).request(Manifest.permission.NFC)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            if (granted) {
                                final Intent intent = new Intent(MainActivity.this, NfcActivity.class);
                                RxActivityResult.startActivityForResult(MainActivity.this, intent, REQUEST_CODE_RECORD_NFC)
                                        .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Observer<ActivityResult>() {
                                            Disposable d;

                                            @Override
                                            public void onSubscribe(Disposable d) {
                                                this.d = d;
                                            }

                                            @Override
                                            public void onNext(final ActivityResult activityResult) {
                                                if (activityResult.getRequestCode() != REQUEST_CODE_RECORD_NFC)
                                                    return;
                                                if (!d.isDisposed()) {
                                                    d.dispose();
                                                }
                                                if (activityResult != null && activityResult.isOk()) {
                                                    final Intent intent1 = activityResult.getData();
                                                    if (intent1 != null && !TextUtils.isEmpty(intent1.getStringExtra("sResult"))) {
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                System.out.println(intent1.getStringExtra("sResult"));
                                                                JSONObject jsonObject = new JSONObject();
                                                                jsonObject.put("errorCode", 1);
                                                                jsonObject.put("resultInfo", intent1.getStringExtra("sResult"));
                                                                jsCallback(hookKey, jsonObject.toJSONString());
                                                            }
                                                        });
                                                    }
                                                }

                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put("errorCode", 0);
                                                jsonObject.put("errorInfo", e.toString());
                                                jsCallback(hookKey, jsonObject.toJSONString());
                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });
                            } else {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                jsCallback(hookKey, jsonObject.toJSONString());
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                                return;
                            }
                        }
                    });
        }

        //NFC写卡
        @JavascriptInterface
        public void handleWriteNFC(final String hookKey, final String billNo) {
            RxPermissions.getInstance(context).request(Manifest.permission.NFC)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            if (granted) {
                                final Intent intent = new Intent(MainActivity.this, NfcActivity.class);
                                intent.putExtra("billNo", billNo);
                                RxActivityResult.startActivityForResult(MainActivity.this, intent, REQUEST_CODE_RECORD_NFC)
                                        .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Observer<ActivityResult>() {
                                            Disposable d;

                                            @Override
                                            public void onSubscribe(Disposable d) {
                                                this.d = d;
                                            }

                                            @Override
                                            public void onNext(final ActivityResult activityResult) {
                                                if (activityResult.getRequestCode() != REQUEST_CODE_RECORD_NFC)
                                                    return;
                                                if (!d.isDisposed()) {
                                                    d.dispose();
                                                }
                                                if (activityResult != null && activityResult.isOk()) {
                                                    final Intent intent1 = activityResult.getData();
                                                    if (intent1 != null && !TextUtils.isEmpty(intent1.getStringExtra("sResult"))) {
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                System.out.println(intent1.getStringExtra("sResult"));
                                                                JSONObject jsonObject = new JSONObject();
                                                                jsonObject.put("errorCode", 1);
                                                                jsonObject.put("resultInfo", intent1.getStringExtra("sResult"));
                                                                jsCallback(hookKey, jsonObject.toJSONString());
                                                            }
                                                        });
                                                    }
                                                }

                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put("errorCode", 0);
                                                jsonObject.put("errorInfo", e.toString());
                                                jsCallback(hookKey, jsonObject.toJSONString());
                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });
                            } else {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                jsCallback(hookKey, jsonObject.toJSONString());
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                                return;
                            }
                        }
                    });
        }

        //文件上传
        @JavascriptInterface
        public void handlerFileUpload(final String hookKey, final String type) {
            webHookKey = hookKey;
            RxPermissions.getInstance(context).request(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean granted) throws Exception {
                            if (granted) {
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType(type);
                                startActivityForResult(intent, REQUEST_CODE_RECORD_FILE);
                            } else {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("errorCode", 0);
                                jsonObject.put("errorInfo", "授权失败");
                                jsCallback(hookKey, jsonObject.toJSONString());
                                //拒绝后弹出的弹窗
                                showPermissionDialog(
                                        getResources().getString(R.string.camera_permission) + getResources().getString(R.string.permission),
                                        getResources().getString(R.string.dialog_cancle_text),
                                        getResources().getString(R.string.dialog_open_text), "");
                                return;
                            }
                        }
                    });
        }

        //跳转到拨号界面
        @JavascriptInterface
        public void handlerCallPhone(final String phoneNum) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + phoneNum);
            intent.setData(data);
            startActivity(intent);
        }

        //附件下载
        @JavascriptInterface
        public void handlerDownloadFile(final String url, final String fileName) {
            try {
                //创建下载任务,downloadUrl就是下载链接
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.allowScanningByMediaScanner();
                request.setVisibleInDownloadsUi(true);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                //指定下载路径和下载文件名
                request.setDestinationInExternalPublicDir("/download/", fileName);
                //获取下载管理器
                DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //将下载任务加入下载队列，否则不会进行下载
                downloadManager.enqueue(request);
            } catch (Exception exception) {
                try {
                    openBrowser(context, url);
                } catch (Exception e) {
                    Toast.makeText(context.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        if (data == null && requestCode != REQUEST_CODE_RECORD_CAMERA) {
            finish();
            return;
        }
        Uri uri = null;
        String path = null;
        if (requestCode != REQUEST_CODE_RECORD_CAMERA) {
            uri = data.getData();
        }
        switch (requestCode) {
            case REQUEST_CODE_RECORD_CAMERA:
                try {
                    new PictureCompressUtil().compressByQuality(imageFilePath, imageFilePath, 1024, false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                uploadOk(new File(imageFilePath), this.getString(R.string.upload_image_url), webHookKey);
                break;
            case REQUEST_CODE_RECORD_ALBUM:
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    path = UriUtils.getPath(this, uri);
                }
                try {
                    new PictureCompressUtil().compressByQuality(path, path, 1024, false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                uploadOk(new File(path), this.getString(R.string.upload_image_url), webHookKey);
                break;
            case REQUEST_CODE_RECORD_FILE:
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    path = UriUtils.getPath(this, uri);
                }
                uploadOk(new File(path), this.getString(R.string.upload_image_url), webHookKey);
                break;
            case REQUEST_CODE_RECORD_VIDEO:
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    path = UriUtils.getPath(this, uri);
                }
                uploadOk(new File(path), this.getString(R.string.upload_image_url), webHookKey);
                break;
        }
    }

    /**
     * 原生回调js方法
     *
     * @param hookKey
     * @param json
     */
    public void jsCallback(final String hookKey, final String json) {
        if (webView == null || TextUtils.isEmpty(hookKey))
            return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:appCallback('" + hookKey + "','" + json + "')");
            }
        });
    }

    //高德定位
    public static AMapLocationClient locationClient = null;
    private static AMapLocationClientOption locationOption = null;
    //定位结果
    public static String locationResult = "";

    private void location() {
        RxPermissions.getInstance(MainActivity.this).request(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            AMapLocationClient.updatePrivacyShow(MainActivity.this, true, true);
                            AMapLocationClient.updatePrivacyAgree(MainActivity.this, true);
                            if (locationClient == null) {
                                locationClient = new AMapLocationClient(MainApplication.getIns());
                            }
                            if (locationOption == null) {
                                //初始化定位参数
                                locationOption = new AMapLocationClientOption();
                                //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
                                locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
                                locationOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
                                locationOption.setLocationCacheEnable(false);//关闭缓存机制
                            }
                            locationClient.setLocationListener(new AMapLocationListener() {
                                @Override
                                public void onLocationChanged(AMapLocation amapLocation) {
                                    if (amapLocation == null)
                                        return;
                                    MyLog.i("定位返回信息：" + amapLocation);
                                    com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
                                    if (amapLocation.getErrorCode() == 0) {
                                        //解析amapLocation获取相应内容。
                                        String longitude = amapLocation.getLongitude() + "";
                                        String latitude = amapLocation.getLatitude() + "";
                                        String province = amapLocation.getProvince();
                                        String city = amapLocation.getCity();
                                        String location = amapLocation.getCity();
                                        if (!TextUtils.isEmpty(location)) {
                                            location = location.replace("市", "");
                                        }
                                        String district = amapLocation.getDistrict();
                                        String adCode = amapLocation.getAdCode();
                                        MyLog.i("定位" + "经纬度：" + longitude + "," + latitude + "地理位置：" + province + "-" + city + "-" + district +
                                                "城市编码：" + adCode);
                                        com.alibaba.fastjson.JSONObject locationObj = new com.alibaba.fastjson.JSONObject();
                                        locationObj.put("longitude", longitude);
                                        locationObj.put("latitude", latitude);
                                        locationObj.put("country", amapLocation.getCountry());
                                        locationObj.put("province", province);
                                        locationObj.put("city", city);
                                        locationObj.put("cityCode", amapLocation.getCityCode());
                                        locationObj.put("district", amapLocation.getDistrict());
                                        locationObj.put("adCode", amapLocation.getAdCode());
                                        locationObj.put("address", amapLocation.getAddress());
                                        object.put("location", locationObj);
                                        object.put("errorCode", 1);
                                        object.put("errorInfo", "");
                                    } else {
                                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                                        MyLog.i("AmapError", "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo());
                                        object.put("errorCode", 0);
                                        object.put("errorInfo", amapLocation.getErrorInfo());
                                    }
                                    locationResult = object.toJSONString();
                                    if (!TextUtils.isEmpty(javascriptObject.locationHook)) {
                                        MainActivity.this.jsCallback(javascriptObject.locationHook, locationResult);
                                        javascriptObject.locationHook = null;
                                    }
                                    locationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                                }
                            });
                            locationClient.startLocation();
                        } else {
                            com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
                            object.put("errorCode", 0);
                            object.put("errorInfo", "授权失败");
                            if (!TextUtils.isEmpty(javascriptObject.locationHook)) {
                                MainActivity.this.jsCallback(javascriptObject.locationHook, object.toJSONString());
                                javascriptObject.locationHook = null;
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 文件上传
     */
    public void uploadOk(final File file, String Url, final String hookKey) {
        loadingManager.show("上传中");
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                .build();

        //设置上传文件以及文件对应的MediaType类型
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

        /**区别：
         * addFormDataPart:   上传key:value形式
         * addPart:  只包含value数据
         */
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//设置文件上传类型
                .addFormDataPart("platform", "4")//文件在服务器中保存的文件夹路径
                .addFormDataPart("file", file.getName(), requestBody)//包含文件名字和内容
                .build();

        Request request = new Request.Builder().url(Url).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadingManager.hide(null);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                file.delete();
                loadingManager.hide(null);
                String str = response.body().string();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("errorCode", 1);
                jsonObject.put("resultInfo", JSONObject.parseObject(str));
                jsCallback(hookKey, jsonObject.toJSONString());
            }
        });
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !webView.canGoBack()) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return false;
    }

}
